<template>
    <div style="width: 800px; padding: 3px; margin: 5px;">
      <el-button type="primary" @click="state.dialogVisible = true">新建课程</el-button>
      <div class="card">
        <el-card style="max-width: 300px"  v-for="item in state.courseList" :key="item.id" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>{{item.name}}</span>
            </div>
          </template>
          <div class="courseBody">
            <div class="courseCover">
              <el-image style="width: 100px; height: 141px" :src="item.cover_front" fit="fill" @click="handleImageClick(item.id)" 
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"/>
            </div>
              <div class="courseContent"> 
              <span>共{{ item.question_count }}道题</span>
              <span>作者：{{ item.owner_name }}</span>
              <span>
                协作者：<br>
                  <template v-for="(name,index) in item.teamworker_name" :key="index">
                    {{ name }}<br>
                  </template>
              </span>
              <span>{{ item.add_time }}</span>
              <el-button type="warning" size="small" @click="onClickAddCooperate(item.id)">邀请协作</el-button>
              </div>
          </div>
              
        </el-card>
      </div>
      <el-dialog
        v-model="state.dialogVisible"
        title="输入课程名"
        width="500"       
      >
        <el-input v-model="inputCourseName" style="width: 240px" placeholder="输入课程名" />       
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="state.dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="addCourse">
              确定
            </el-button>
          </div>
        </template>
      </el-dialog>
      
      <el-dialog
        v-model="state.dialogVisibleCooperation"
        title="邀请协作者"
        width="500"       
      >
      <div>
        <el-input v-model="state.inputPhone" style="width: 240px" placeholder="输入手机号码" :suffix-icon="Search" /> 
        <el-button type="primary" @click="onClickSearchUser"> 搜索 </el-button>
      </div>
        <div v-if="Object.keys(state.invitor).length > 0">
          <span>邀请他:</span>    
          <el-button type="warning" @click="onClickInviteHim()" text>{{ state.invitor.username }}</el-button>
        </div>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="state.dialogVisibleCooperation = false">取消</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
    
</template>
<script setup>
    // 引入
  import {reactive, onMounted, ref} from 'vue'
  import axios from '@/utils/axios'
  import { ElMessage } from 'element-plus'
  import { useStore } from 'vuex'
  import { useRoute, useRouter } from 'vue-router'
  import { Search } from '@element-plus/icons-vue'
  const router = useRouter()
  const store=useStore()
  const inputCourseName = ref('')
  const defaultProps = {
    children: 'children',
    label: 'label',
  }
  // 通用变量
  const state = reactive({
      nodeTree: [],
      dialogVisible: false,
      courseList: [],
      teamworker: [],
      dialogVisibleCooperation: false,
      invitor: {},
      inputPhone: '',
      selectCourse: 0,
  })
  // 点击邀请协作按钮
  const onClickAddCooperate = (course)=>{
    state.dialogVisibleCooperation = true
    state.selectCourse = course
  }
  // 点击搜索邀请者
  const onClickSearchUser = ()=>{
    console.log('搜索邀请者')
    let params = {
      phoneNumber: state.inputPhone,
    }
    axios.get(`/UserModelViewSet/phone_number_exit/`, {params}).then((res) => {
      console.log('查找结果：', res.data.results)
      if(res.code==200){
        ElMessage.success( '查找成功')
        state.invitor = res.data.results 
      }else
      if(res.code==1099){
        ElMessage.warning( '找不到')
      }
      else{
        console.log("提交失败", res)
      }       
    }).catch((error)=>{
      console.log("错误：", error)
    })
  }
  // 确定邀请他
  const onClickInviteHim = ()=>{
    console.log('发送后端邀请他', state.invitor.username)
    let params = {
        node: state.selectCourse,
        user: state.invitor.id,
    }
    axios.post(`/NodeCooperationViewSet/create_node_cooperation/`, params).then((res) => {
      if(res.code==200){
        ElMessage.success( '创建成功')     
        state.dialogVisibleCooperation = false;
        state.inputPhone = ''
        state.invitor = {}
        getAllCourse()
      }else
      if(res.code==1099){
        ElMessage.warning( '服务器返回创建失败！')
      }
      else
      if(res.code==1098){
        ElMessage.warning( '该教师已经被邀请！')
      }
      else
      if(res.code==1097){
        ElMessage.warning( '这是作者，没必要邀请')
      }
      else{
        console.log("提交失败", res)
      }       
    }).catch((error)=>{
      console.log("错误：", error)
    })
  }
  // 点击新建课程按钮
  const addCourse = () => {
    console.log('新建课程啦')
    let params = {
        name: inputCourseName.value,
    }
    axios.post(`/NodeModelViewSet/create_node/`, params).then((res) => {
      if(res.code==200){
        ElMessage.success( '创建成功')
        state.nodeTree = res.data.results
        state.dialogVisible = false;
        getAllCourse()
      }else
      if(res.code==1099){
        ElMessage.warning( '标题不能为空！')
      }
      else{
        console.log("提交失败", res)
      }       
    }).catch((error)=>{
      console.log("错误：", error)
    })
  }
  // 点击节点事件
  const handleNodeClick = (data) => {
    console.log(data)
  }
  // 获取所有的课程
  const getAllCourse = () => {
    axios.get(`/NodeModelViewSet/get_all_course/`).then(res => {
      console.log("获取章节结果：",res)
      if (res.code==200){
        state.courseList= res.data.results
      }else
      if(res.code==1099){
        ElMessage.error('结果为空')
        return false
      }else{
        ElMessage.error('服务器错误')
      } 
    })
    .catch((error)=>{
      console.log("error:", error)
    })   
  }

  onMounted(()=>{    
    getAllCourse()
  })
  const handleImageClick=(id) => {
    console.log('跳转啦')
    store.commit('setNodeId', id)
    router.push(`/showQuestionPrivate`)
  }
</script>
 
<style scoped>
  .courseBody{
    display: flex;
    flex-direction: row;
    margin: 2px;
  }
  .courseContent{
    display: flex;
    flex-direction: column;
    padding:2px;
    font-size: smaller;
  }
  .card{
    display: flex;
    flex-direction: row;
    margin: 5px;
  }
</style>